package com.project.class8_24.proxy.model.service.impl;

import com.project.class8_24.proxy.model.dao.IClassDao;
import com.project.class8_24.proxy.model.dao.IUserDao;
import com.project.class8_24.proxy.model.dao.impl.ClassDaoImpl;
import com.project.class8_24.proxy.model.dao.impl.UserDaoImpl;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class ServiceProxyFactory implements InvocationHandler {
    private static Map<String,Object> daoMap = new HashMap<>();
    static{
        File file = new File("src/main/java/com/project/class8_24/proxy/model/dao/impl");
        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                if (f.isFile() && f.getName().lastIndexOf(".java") != -1) {
                    //得到文件类全路径
                    String className = "com.project.class8_24.proxy.model.dao.impl." +
                            f.getName().substring(0, f.getName().lastIndexOf("."));
                    //加载类，得到类模版
                    Class c = Class.forName(className);
                    //调用无参构造方法，产生对象
                    Object daoObj = c.getConstructor().newInstance();
                    //得到对象实现的接口列表
                    Class[] classArray = daoObj.getClass().getInterfaces();
                    if(classArray.length == 1) {
                        //以接口名称做键，以DAO对象做值，加入map
                        daoMap.put(classArray[0].getSimpleName(), daoObj);
                    }
                }
            }
            System.out.println(daoMap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private Object targetObj;
    public  ServiceProxyFactory(Object targetObj){
        this.targetObj = targetObj;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Field[] fieldArray = targetObj.getClass().getDeclaredFields();
//        for(Field f : fieldArray){
//            f.setAccessible(true);
//            //得到属性类型
//            Class typeClass = f.getType();
//            //得到该属性对应的值
//            Object daoObj = daoMap.get(typeClass.getSimpleName());
//            //将目标对象的属性实例化
//            f.set(targetObj,daoObj);
//        }
        for(Field f : fieldArray){
            f.setAccessible(true);
            if(f.getType() == IUserDao.class){
                f.set(targetObj,new UserDaoImpl());
            }
            else if(f.getType() == IClassDao.class){
                f.set(targetObj,new ClassDaoImpl());
            }
        }


        //执行目标方法
        Object returnObj = method.invoke(targetObj,args);

        return returnObj;
    }


}
